/*
 * Copyright 2011 Holger Brandl
 *
 * This code is licensed under BSD. For details see
 * http://www.opensource.org/licenses/bsd-license.php
 */

package info.rflow.connectors;


import info.rflow.Utils;
import info.rflow.preferences.ExecutionModelSettings;

import java.io.IOException;
import java.util.logging.Level;


/**
 * A connector using apple script
 *
 * @author Holger Brandl
 */
public class AppleScriptConnector implements CodeLaunchConnector {

    @Override
    public void submitCode(String rCommands, boolean switchFocus2R) {
        try {
            if (Utils.isMacOSX()) {
                Runtime runtime = Runtime.getRuntime();

                String dquotesExpandedText = rCommands.replace("\\", "\\\\");
                dquotesExpandedText = dquotesExpandedText.replace("\"", "\\\"");

                String evalTarget = Utils.getPrefs().get(ExecutionModelSettings.PUSH_TARGET, ExecutionModelSettings.getDefaultPushTarget());

//                http://stackoverflow.com/questions/1870270/sending-commands-and-strings-to-terminal-app-with-applescript
                String evalSelection;
                if (evalTarget.equals("Terminal")) {
                    evalSelection = switchFocus2R ? "tell application \"Terminal\" to activate\n" : "";
                    evalSelection += "tell application \"" + "Terminal" + "\" to do script \"" + dquotesExpandedText + "\" in window 0";

                } else {
                    evalSelection = switchFocus2R ? "tell application \"" + evalTarget + "\" to activate\n" : "";
                    evalSelection += "tell application \"" + evalTarget + "\" to cmd \"" + dquotesExpandedText + "\"";
                }

                String[] args = {"osascript", "-e", evalSelection};

                runtime.exec(args);
            }
        } catch (IOException e1) {
            Utils.log(Level.SEVERE, e1.toString());
        }
    }


    public static void main(String[] args) {
        new AppleScriptConnector().submitCode("write.table(head(iris), file=\"~/Desktop/iris.txt\", sep=\"\\t\")\n", false);
    }
}
